//
//  HQYFoodViewController.m
//  Go!
//
//  Created by rimi on 16/7/11.
//  Copyright © 2016年 黄秋燕. All rights reserved.
//

#import "HQYFoodViewController.h"
#import "HQYFoodSelectCell.h" // 选择按钮
#import "HQYFoodScrollView.h" // 广告轮播图
#import "HQYSearchViewController.h" // 搜索页面控制器
#import "HQYFoodTableModel.h" // 列表模型
#import "HQYFoodTableCell.h" // 列表cell
#import "UIImageView+WebCache.h" // 图片缓存
#import "HQYFoodKindViewController.h" // 美食类别二级页面
#import "HQYHomeCellDetailViewController.h" // 美食三级页面

#define cellId @"kCellIdKey"
#define tableviewCellId @"kTableviewCellIdKey"

@interface HQYFoodViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView *backgroundHeadView; /**< 背景底部作为tableView的头视图 */

#pragma mark --选择按钮
@property (nonatomic, strong) NSArray *selectBtnArray; /**< 选择按钮图片/名字数组 */
@property (nonatomic, strong) NSArray *selectBtnIdArray; /**< 按钮的团单类别ID */
@property (nonatomic, strong) UICollectionView *selectCollectionView; /**< 选择按钮的集合视图 */

#pragma mark --广告轮播图
@property (nonatomic, strong) HQYFoodScrollView *scrollView; /**< 美食轮播图 */

#pragma mark --表格视图
@property (nonatomic, strong) UITableView *tableView; /**< 美食表格视图 */
@property (nonatomic, strong) NSArray *tableModelArray; /**< 列表数据数组 */
@property (nonatomic, strong) HQYFoodTableModel *model; /**< 数据模型 */
@end

@implementation HQYFoodViewController

- (void)dealloc {
    // 移除观察者
    [self.model removeObserver:self forKeyPath:@"response"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeDataSource];
    [self initializeUserInterface];
}

#pragma mark - initialize
// 监听到状态变化会执行该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"response"]) {
        self.tableModelArray = [self.model getDataArray];
        [self.tableView reloadData];
    }
}

/**< 初始化数据源 */
- (void)initializeDataSource {
    _selectBtnArray = @[@"中餐", @"快餐", @"西餐", @"海鲜", @"火锅", @"蛋糕", @"咖啡", @"其他"];
    _selectBtnIdArray = @[@"962", @"380", @"391", @"439", @"364", @"881", @"954", @"327"];
    [self.model getList];
    [self.model addObserver:self forKeyPath:@"response" options:NSKeyValueObservingOptionNew context:nil];
}

/**< 初始化用户界面 */
- (void)initializeUserInterface {
    self.view.backgroundColor = ColorWith(232, 232, 232);
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    /**< 搜索按钮 */
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[IMAGE(@"搜索-红-55") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(clickSearchItem)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    // 注册原型cell
    [self.selectCollectionView registerClass:[HQYFoodSelectCell class] forCellWithReuseIdentifier:cellId];
    //注册原型cell（xib模式）
    [self.tableView registerNib:[UINib nibWithNibName:@"HQYFoodTableCell" bundle:nil] forCellReuseIdentifier:tableviewCellId];

    [self.view addSubview:self.tableView];
    // 将背景图作为tableview的头部视图
    [self.backgroundHeadView addSubview:self.selectCollectionView];
    [self.backgroundHeadView addSubview:self.scrollView];
    self.backgroundHeadView.bounds = CGRectMake(0, 0, ScreenW, CGRectGetMaxY(self.scrollView.frame) + tableView_Interval);
    self.tableView.tableHeaderView = self.backgroundHeadView;
}

#pragma mark - 搜索按钮监听
- (void)clickSearchItem {
    HQYSearchViewController *searchVC = [[HQYSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - <UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
//返回每组多少个格子
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 8;
}

//返回格子视图
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HQYFoodSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.iconImg.image = IMAGE(self.selectBtnArray[indexPath.item]);
    cell.iconName.text = self.selectBtnArray[indexPath.item];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HQYFoodKindViewController *detailVC = [[HQYFoodKindViewController alloc] init];
    detailVC.classId = @"326";
    detailVC.foodId = _selectBtnIdArray[indexPath.row];
    detailVC.title = _selectBtnArray[indexPath.row];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>
// 返回有多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.tableModelArray.count;
}

// 每组多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ((NSArray *)self.tableModelArray[section][@"shops"]).count;
}

// 每行是什么
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HQYFoodTableCell *cell = [tableView dequeueReusableCellWithIdentifier:tableviewCellId];
    
    NSDictionary *dict = self.tableModelArray[indexPath.section][@"shops"][indexPath.row];
    
    [cell.foodIconImage sd_setImageWithURL:[NSURL URLWithString:dict[@"icon"]] placeholderImage:IMAGE(@"等待中")];
    cell.foodNameLabel.text = dict[@"name"];
    cell.foodPriceLabel.text = dict[@"price"];
    cell.foodSellNumLabel.text = dict[@"sellNum"];
    
    return cell;
}

// 组头视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return Size_H(50);
}

// 组底部视图高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

// 返回组模式下每个组头视图的代理方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, Size_H(50))];
    headView.backgroundColor = [UIColor whiteColor];
    
    UILabel_Font *shopNameLabel = [[UILabel_Font alloc] initWithFrame:CGRectMake(Size_W(12), 0, headView.frame.size.width, headView.frame.size.height)];
    shopNameLabel.font = [UIFont systemFontOfSize:Font(20)];
    NSDictionary *dict = self.tableModelArray[section];
    shopNameLabel.text = dict[@"shopName"];
    [headView addSubview:shopNameLabel];
    
    return headView;
}

// 点击时的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HQYHomeCellDetailViewController *detailVC = [[HQYHomeCellDetailViewController alloc] init];
    detailVC.dict = _tableModelArray[indexPath.section][@"shops"][indexPath.row];
    detailVC.url = _tableModelArray[indexPath.section][@"shops"][indexPath.row][@"url"];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - Getter
/**< 美食表格视图 */
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - Size_H(49)) style:UITableViewStyleGrouped];
        _tableView.rowHeight = Size_H(80);
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

/**< 背景底部作为tableView的头视图 */
- (UIView *)backgroundHeadView {
    if (!_backgroundHeadView) {
        _backgroundHeadView = [[UIScrollView alloc] init];
        _backgroundHeadView.frame = CGRectMake(0, 0, ScreenW, ScreenH - 49);
    }
    return _backgroundHeadView;
}

/**< 选择按钮的集合视图 */
- (UICollectionView *)selectCollectionView {
    if (!_selectCollectionView) {
        //初始化一个布局Layout对象
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置最小行距
        layout.minimumLineSpacing = 1;
        //设置最小间距
        layout.minimumInteritemSpacing = 1;
        //设置格子大小
        layout.itemSize = CGSizeMake((ScreenW - 3)/4.0, (ScreenW - 3)/5);
        
        _selectCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), ScreenW, (ScreenW - 3)/2.5) collectionViewLayout:layout];
        //设置代理和数据源
        _selectCollectionView.dataSource = self;
        _selectCollectionView.delegate = self;
        _selectCollectionView.scrollEnabled = NO;
        _selectCollectionView.backgroundColor = ColorWith(232, 232, 232);
    }
    return _selectCollectionView;
}

/**< 美食轮播图 */
- (HQYFoodScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[HQYFoodScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.selectCollectionView.frame) + tableView_Interval, ScreenW, Size_H(120))];
        _scrollView.vc= self;
    }
    return _scrollView;
}

- (HQYFoodTableModel *)model {
    if (!_model) {
        _model = [[HQYFoodTableModel alloc] init];
    }
    return _model;
}
@end
